package com.xjrsoft.module.customer.erp_model.eRP_InStock.service.impl;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.dbmodel.utils.DataSourceUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.dto.ErpStockinstockentryDto;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.entity.ErpStockinstock;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.entity.ErpStockinstockentry;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.mapper.ErpStockinstockentryMapper;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.dto.ErpStockinstockListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.mapper.ErpStockinstockMapper;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.service.IErpStockinstockService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.module.customer.erp_model.eRP_InStock.vo.ErpStockinstockentryVo;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.entity.ErpInventory;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.service.impl.ErpInventoryServiceImpl;
import com.xjrsoft.module.customer.erp_model.goodsManage.entity.ErpGoods;
import com.xjrsoft.module.customer.erp_model.goodsManage.service.impl.ErpGoodsServiceImpl;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
 *  服务实现类
 *
 * @author pp
 * @since 2021-10-08
 */
@Service
@AllArgsConstructor
public class ErpStockinstockServiceImpl extends BaseService<ErpStockinstockMapper, ErpStockinstock> implements IErpStockinstockService {

	private ErpStockinstockentryMapper erpStockinstockentryMapper;

	@Autowired
	private ErpGoodsServiceImpl erpGoodsService;
	@Autowired
	private ErpInventoryServiceImpl erpInventoryService;

	@Override
	public IPage<ErpStockinstock> getPageList(ErpStockinstockListDto pageListDto) {
		Wrapper<ErpStockinstock> wrapper = Wrappers.<ErpStockinstock>query().lambda()				.eq(!StringUtil.isEmpty(pageListDto.getF_InStockCode()), ErpStockinstock::getFInstockcode, pageListDto.getF_InStockCode())
				.ge(!StringUtil.isEmpty(pageListDto.getF_InStockDate_Start()), ErpStockinstock::getFInstockdate, pageListDto.getF_InStockDate_Start())
				.le(!StringUtil.isEmpty(pageListDto.getF_InStockDate_End()), ErpStockinstock::getFInstockdate, pageListDto.getF_InStockDate_End())
				.eq(!StringUtil.isEmpty(pageListDto.getF_WarehouseId()), ErpStockinstock::getFWarehouseid, pageListDto.getF_WarehouseId());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@SneakyThrows
	@Override
	public String addErpStockinstock(ErpStockinstock erpStockinstock, List<ErpStockinstockentryDto> erpStockinstockentryDtos, List<ErpStockinstockentry> erpStockinstockentryList) {
		updateInfo(erpStockinstock,erpStockinstockentryDtos);
		String erpStockinstockId = IdWorker.get32UUID();
		erpStockinstock.setFId(erpStockinstockId);
		erpStockinstockentryList.forEach(erpStockinstockentry -> erpStockinstockentry.setFInstockid(erpStockinstockId));
		this.saveBatch(erpStockinstockentryList,  ErpStockinstockentry.class, ErpStockinstockentryMapper.class);
		boolean isSuccess = this.save(erpStockinstock);
		return isSuccess ? erpStockinstockId : null;
	}
	public  boolean updateInfo(ErpStockinstock erpStockinstock,List<ErpStockinstockentryDto> erpStockinstockentryDtos) throws SQLException {
		for (int i=0;i<erpStockinstockentryDtos.size();i++)
		{
			//入库单位和基本单位和库存显示单位都一样可以直接做操作  1.对库存做操作（新增或修改）
			if(erpStockinstockentryDtos.get(i).getFBasicunit().equals(erpStockinstockentryDtos.get(i).getFUnitid())&&erpStockinstockentryDtos.get(i).getFComunit().equals(erpStockinstockentryDtos.get(i).getFUnitid()))
			{
				//先判断goodsid是否为空，为空的话就先添加商品，再在对应仓库里做新增 如果不为空 代表有此商品 直接修改库存
				if(erpStockinstockentryDtos.get(i).getFGoodsid().equals("")||erpStockinstockentryDtos.get(i).getFGoodsid()==null)
				{
					ErpGoods erpGoods=new ErpGoods();
//					String erpGoodsId=IdWorker.get32UUID();
//					erpGoods.setFId(erpGoodsId);
					erpGoods.setFFullname(erpStockinstockentryDtos.get(i).getFGoodsname());
					erpGoods.setFEncode(erpStockinstockentryDtos.get(i).getFGoodcode());
					erpGoods.setFSpecs(erpStockinstockentryDtos.get(i).getFSpecs());
					erpGoods.setFComunit(erpStockinstockentryDtos.get(i).getFComunit());
					erpGoods.setFBasicunit(erpStockinstockentryDtos.get(i).getFBasicunit());
					erpGoods.setFInunit(erpStockinstockentryDtos.get(i).getFUnitid());
					erpGoods.setFOutunit(erpStockinstockentryDtos.get(i).getFOutunit());
					erpGoods.setFDescription(erpStockinstockentryDtos.get(i).getFDescription());
					erpGoodsService.addErpGoods(erpGoods);

					ErpInventory erpInventory=new ErpInventory();
					erpInventory.setFGoodsid(erpGoods.getFId());
					erpInventory.setFWarehouseid(erpStockinstock.getFWarehouseid());
					erpInventory.setFBasicamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()));
					erpInventory.setFComamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()));
					erpInventoryService.addErpInventory(erpInventory);

				}
				else
				{
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpStockinstock.getFWarehouseid()+ "' and i.F_GoodsId='"+erpStockinstockentryDtos.get(i).getFGoodsid()+"'";
					List<Entity> isInventory1= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
					ErpInventory erpInventory1=new ErpInventory();
					erpInventory1.setFGoodsid(erpStockinstockentryDtos.get(i).getFGoodsid());
					erpInventory1.setFWarehouseid(erpStockinstock.getFWarehouseid());
					//如果有的话就修改对应商品的库存
					if (isInventory1.size()>0)
					{
						BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
						BigDecimal quantity=new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity());
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFBasicamount(aftBasicQua.add(quantity));
						erpInventory1.setFComamount(aftComamQua.add(quantity));
						//怎么在一个serveimp里去调用另外一个里面的方法 一定要注入
						erpInventoryService.updateById(erpInventory1);
					}
					else
					{
						erpInventory1.setFBasicamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()));
						erpInventory1.setFComamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()));
						erpInventoryService.addErpInventory(erpInventory1);
					}
				}
			}
			//不一样先查询换算率得到之后转换
			else {
				//这里组合有四种情况  只有同时满足不相等的情况 才需要同时转换
				//基本单位转换率
				BigDecimal baseConverRate = null;
				//显示单位转换率
				BigDecimal comConverRate=null;
				if(!erpStockinstockentryDtos.get(i).getFBasicunit().equals(erpStockinstockentryDtos.get(i).getFUnitid()) &&!erpStockinstockentryDtos.get(i).getFComunit().equals(erpStockinstockentryDtos.get(i).getFUnitid()))
				{
					//查询转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpStockinstockentryDtos.get(i).getFUnitid()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);
					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpStockinstockentryDtos.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpStockinstockentryDtos.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//先判断goodsid是否为空，为空的话就先添加商品，再在对应仓库里做新增 如果不为空 代表有此商品 直接修改库存
					if(erpStockinstockentryDtos.get(i).getFGoodsid().equals("")||erpStockinstockentryDtos.get(i).getFGoodsid()==null)
					{
						ErpGoods erpGoods=new ErpGoods();
//					String erpGoodsId=IdWorker.get32UUID();
//					erpGoods.setFId(erpGoodsId);
						erpGoods.setFFullname(erpStockinstockentryDtos.get(i).getFGoodsname());
						erpGoods.setFEncode(erpStockinstockentryDtos.get(i).getFGoodcode());
						erpGoods.setFSpecs(erpStockinstockentryDtos.get(i).getFSpecs());
						erpGoods.setFComunit(erpStockinstockentryDtos.get(i).getFComunit());
						erpGoods.setFBasicunit(erpStockinstockentryDtos.get(i).getFBasicunit());
						erpGoods.setFInunit(erpStockinstockentryDtos.get(i).getFUnitid());
						erpGoods.setFOutunit(erpStockinstockentryDtos.get(i).getFOutunit());
						erpGoods.setFDescription(erpStockinstockentryDtos.get(i).getFDescription());
						erpGoodsService.addErpGoods(erpGoods);
						ErpInventory erpInventory=new ErpInventory();
						erpInventory.setFGoodsid(erpGoods.getFId());
						erpInventory.setFWarehouseid(erpStockinstock.getFWarehouseid());
						erpInventory.setFBasicamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()).multiply(baseConverRate));
						erpInventory.setFComamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()).multiply(comConverRate));
						erpInventoryService.addErpInventory(erpInventory);
					}
					else
					{
						//得到转换率之后开始转换
						//根据商品id和仓库id查询是否有此商品的库存数据
						String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpStockinstock.getFWarehouseid()+ "' and i.F_GoodsId='"+erpStockinstockentryDtos.get(i).getFGoodsid()+"'";
						List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
						ErpInventory erpInventory1=new ErpInventory();
						BigDecimal quantity=new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity());
						erpInventory1.setFWarehouseid(erpStockinstock.getFWarehouseid());
						erpInventory1.setFGoodsid(erpStockinstockentryDtos.get(i).getFGoodsid());
						//如果有的话就修改对应商品的库存
						if (isInventory1.size()>0)
						{
							//修改数量=原有的数据+本次入库的数量*转换率
							erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
							BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
							BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
							erpInventory1.setFBasicamount(aftBasicQua.add(quantity.multiply(baseConverRate)));
							erpInventory1.setFComamount(aftComamQua.add(quantity.multiply(comConverRate)));
							erpInventoryService.updateById(erpInventory1);
						}
						else
						{
							erpInventory1.setFBasicamount(quantity.multiply(baseConverRate));
							erpInventory1.setFComamount(quantity.multiply(comConverRate));
							erpInventoryService.addErpInventory(erpInventory1);
						}
					}
				}
				else {
					//其中一个需要转换 先判断是基本数量单位需要转换还是库存显示单位需要转换
					//如果库存显示单位和入库单位不相等 就需要转换,否则就是基本单位需要转换
					//先查询出转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpStockinstockentryDtos.get(i).getFUnitid()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);

					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpStockinstockentryDtos.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpStockinstockentryDtos.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//先判断goodsid是否为空，为空的话就先添加商品，再在对应仓库里做新增 如果不为空 代表有此商品 直接修改库存
					if(erpStockinstockentryDtos.get(i).getFGoodsid().equals("")||erpStockinstockentryDtos.get(i).getFGoodsid()==null)
					{
						ErpGoods erpGoods=new ErpGoods();
//					String erpGoodsId=IdWorker.get32UUID();
//					erpGoods.setFId(erpGoodsId);
						erpGoods.setFFullname(erpStockinstockentryDtos.get(i).getFGoodsname());
						erpGoods.setFEncode(erpStockinstockentryDtos.get(i).getFGoodcode());
						erpGoods.setFSpecs(erpStockinstockentryDtos.get(i).getFSpecs());
						erpGoods.setFComunit(erpStockinstockentryDtos.get(i).getFComunit());
						erpGoods.setFBasicunit(erpStockinstockentryDtos.get(i).getFBasicunit());
						erpGoods.setFInunit(erpStockinstockentryDtos.get(i).getFUnitid());
						erpGoods.setFOutunit(erpStockinstockentryDtos.get(i).getFOutunit());
						erpGoods.setFDescription(erpStockinstockentryDtos.get(i).getFDescription());
						erpGoodsService.addErpGoods(erpGoods);
						ErpInventory erpInventory=new ErpInventory();
						erpInventory.setFGoodsid(erpGoods.getFId());
						erpInventory.setFWarehouseid(erpStockinstock.getFWarehouseid());
						erpInventory.setFBasicamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()).multiply(baseConverRate));
						erpInventory.setFComamount(new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity()).multiply(comConverRate));
						erpInventoryService.addErpInventory(erpInventory);
					}
					else
					{
						//得到转换率之后开始转换
						//根据商品id和仓库id查询是否有此商品的库存数据
						String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpStockinstock.getFWarehouseid()+ "' and i.F_GoodsId='"+erpStockinstockentryDtos.get(i).getFGoodsid()+"'";
						List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
						ErpInventory erpInventory1=new ErpInventory();
						//本次入库数量
						BigDecimal quantuty=new BigDecimal(erpStockinstockentryDtos.get(i).getFQuantity());
						erpInventory1.setFGoodsid(erpStockinstockentryDtos.get(i).getFGoodsid());
						erpInventory1.setFWarehouseid(erpStockinstock.getFWarehouseid());
						//修改数量=原有的数据-本次出库的数量*转换率
						//如果有的话就修改对应商品的库存
						if (isInventory1.size()>0)
						{
							BigDecimal aftBasicQua=isInventory1.get(0).getBigDecimal("f_basicamount");
							BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
							erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
							erpInventory1.setFBasicamount(aftBasicQua.add(quantuty));
							erpInventory1.setFComamount(aftComamQua.add(quantuty));
							//是否需要转换 需要的话就重新赋值
							if (!erpStockinstockentryDtos.get(i).getFComunit().equals(erpStockinstockentryDtos.get(i).getFUnit()))
							{
								erpInventory1.setFComamount(aftComamQua.add(quantuty.multiply(comConverRate)));
							}
							else
							{
								erpInventory1.setFBasicamount(aftBasicQua.add(quantuty.multiply(baseConverRate)));
							}
							erpInventoryService.updateById(erpInventory1);
						}
						else
						{
							erpInventory1.setFBasicamount(quantuty);
							erpInventory1.setFComamount(quantuty);
							if (!erpStockinstockentryDtos.get(i).getFComunit().equals(erpStockinstockentryDtos.get(i).getFUnit()))
							{
								erpInventory1.setFComamount(quantuty.multiply(comConverRate));
							}
							else
							{
								erpInventory1.setFBasicamount(quantuty.multiply(baseConverRate));
							}
							erpInventoryService.addErpInventory(erpInventory1);
						}
					}

				}
			}
		}
		return  true;
	}
	@Override
	public boolean updateErpStockinstock(String id, ErpStockinstock erpStockinstock, List<ErpStockinstockentry> erpStockinstockentryList) {
//		erpStockinstock.setFId(id);
//		erpStockinstockentryList.forEach(erpStockinstockentry -> erpStockinstockentry.setFInstockid(id));
//		erpStockinstockentryMapper.delete(Wrappers.<ErpStockinstockentry>query().lambda().eq(ErpStockinstockentry::getFInstockid, id));
//		this.saveBatch(erpStockinstockentryList, ErpStockinstockentry.class, ErpStockinstockentryMapper.class);
//		return this.updateById(erpStockinstock);
		return false;
	}

	public List<ErpStockinstockentry> getErpStockinstockentryByParentId(String parentId){
		Wrapper wrapper = Wrappers.<ErpStockinstockentry>query().lambda().eq(ErpStockinstockentry::getFInstockid, parentId);
		return erpStockinstockentryMapper.selectList(wrapper);
	}
	public List<ErpStockinstockentryVo> getInfo(String parentId){
		return erpStockinstockentryMapper.getInfo(parentId);
	}
}
